package com.zhenfan.pattern;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 节点
 *
 * @author wangmh
 * @create 2018-11-02 15:48
 **/
public class Node implements Cloneable, Serializable {

    /**
     * 数据
     */
    private String data;

    /**
     * 下一个节点
     */
    private Node next;

    public Node(String data, Node next) {
        this.data = data;
        this.next = next;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    /**
     * 浅拷贝（克隆）
     * @return
     */
    @Override
    protected Node clone() {
        try {
            return (Node) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 深拷贝（复制）
     * @return
     */
    public Node copy() {
        Node copy = this.clone();
        copy.next = next.clone();
        return copy;
    }

    /**
     * 使用I/O流复制
     * @return
     */
    public Node ioCopy() {
        File file = new File("io_copy.obj");
        ObjectOutputStream oos = null;
        FileOutputStream fos = null;
        ObjectInputStream ois = null;
        FileInputStream fis = null;
        try {
            fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(this);
            oos.flush();

            fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
            Node copy = (Node) ois.readObject();
            return copy;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
